package me.springboot.mybatis.web;

import me.springboot.mybatis.common.utils.StringUtil;
import me.springboot.mybatis.common.utils.UUIDGenerator;
import me.springboot.mybatis.core.RetCode;
import me.springboot.mybatis.core.RetResponse;
import me.springboot.mybatis.core.RetResult;
import me.springboot.mybatis.exception.ResultException;
import me.springboot.mybatis.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/23.
 */
@RestController
@RequestMapping("/upload")
@Configuration
@CrossOrigin
public class UploadController {

    private static final Logger logger = Logger.getLogger(UploadController.class);

    @Value("${img.localhost}")
    private String location;

    private final ResourceLoader resourceLoader;

    @Autowired
    public UploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostMapping("/img")
    public RetResult uploadImg(@RequestParam("editormd-image-file") MultipartFile multipartFile, HttpServletRequest request) throws ResultException {
        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            throw new ResultException(RetCode.BUS_FALL.getCode(), "文件不能为空");
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            throw new ResultException(RetCode.BUS_FALL.getCode(), "文件格式错误");
        }
        String root_fileName = multipartFile.getOriginalFilename();
        if (StringUtil.isBlank(root_fileName)) {
            throw new ResultException(RetCode.BUS_FALL.getCode(), "文件名不能为空");
        }
        logger.info("上传图片:name=" + root_fileName + ",type=" + contentType);
        String suffixName = root_fileName.substring(root_fileName.lastIndexOf(".") + 1);
        logger.info("上传的后缀名为：" + suffixName);
        //处理图片
//        User currentUser = SessionUtil.getSessionUser(request);
        //获取路径
        String return_path = "";
//        String return_path = getFilePath(currentUser);
        String filePath = location + return_path;
        logger.info("图片保存路径=" + filePath);
        String file_name = null;
        try {
            file_name = saveImg(multipartFile, filePath, suffixName);

            Map<String, Object> resultMap = new HashMap();
            resultMap.put("filePath", filePath + File.separator + file_name);
            resultMap.put("fileName", file_name);
            return RetResponse.makeOKRsp(resultMap);
        } catch (IOException e) {
            throw new ResultException(RetCode.BUS_FALL.getCode(), "保存图片错误");
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(location, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    private String getFilePath(User currentUser) {
        return "";
    }

    /**
     * 保存文件，直接以multipartFile形式
     *
     * @param multipartFile
     * @param path          文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path, String suffixName) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = UUIDGenerator.getUUID() + "." + suffixName;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }

}
